package com.dongdongshop.controller;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dongdongshop.data.Result;
import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.UserService;
import com.dongdongshop.utils.ShiroUtils;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@RequestMapping("/register")
@Controller
public class RegisterController {


    @DubboReference
    private UserService tbUserService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/toRegister")
    public String toRegister(){
        return "register";
    }

    @RequestMapping("/getPhonoMessage")
    @ResponseBody
    public Result sendPhoneMessage(String phone) throws Exception {

        rocketMQTemplate.convertAndSend("Phone-Message-1",phone);

        return Result.OK();
    }
    @RequestMapping("/registerUser")
    @ResponseBody
    public Result registerUser(TbUser user,String code){
        String phone = user.getPhone();
        String codeM = (String) redisTemplate.boundHashOps("message").get(phone);
        //判断验证码是否正确
        if (code.equals(codeM)){
            String s = ShiroUtils.generateSalt(6);
            String md5 = ShiroUtils.encryptPassword("MD5", user.getPassword(), s, 3);
            user.setPassword(md5);
            user.setSalt(s);
            try {
                TbUser userByPname = tbUserService.getUserByPname(user.getUsername());
                if (userByPname == null){
                    tbUserService.insertSeller(user);
                    return Result.OK();
                }else {
                    return Result.response(ResultEnum.ACCOUNT_ALREADY_EXISTS);
                }
            }catch (Exception e){
                return Result.ER();
            }
        }
        return Result.ER().setData("验证码失败");
    }

}
